package Pet.Management.service.impl;

import Pet.Management.common.exception.ServiceException;
import Pet.Management.domain.entity.User;
import Pet.Management.repository.UserRepository;
import Pet.Management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User login(String username, String password) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            // 直接比较密码
            if (password.equals(user.getPassword())) {
                return user;
            }
        }
        return null;
    }

    @Override
    public User getByUsername(String username) {
        return userRepository.findByUsername(username).orElse(null);
    }
    
    @Override
    public User getById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
    
    @Override
    public void updateUser(User user) {
        userRepository.save(user);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userRepository.findByUsername(username).isPresent();
    }

    @Override
    @Transactional
    public User registerUser(User user) {
        // 1. 基本验证
        if (user.getUsername() == null || user.getPassword() == null) {
            throw new IllegalArgumentException("用户名和密码不能为空");
        }

        // 2. 检查用户名是否已存在
        if (existsByUsername(user.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 3. 设置默认值
        if (user.getIsAdmin() == null) {
            user.setIsAdmin((byte) 0); // 默认为普通用户
        }
        if (user.getStatus() == null) {
            user.setStatus((byte) 0); // 默认状态为正常
        }

        // 4. 保存用户
        return userRepository.save(user);
    }
} 